#include "StreamPushServer.h"
#include "ProtocolApi.h"
#include "StreamApi.h"

using namespace Protocol;
using namespace Stream;

void StreamPushServerInit(){
	StreamPushServer::instance();
}

StreamPushServer *StreamPushServer::instance(){
    static StreamPushServer * pusher = new StreamPushServer();
    return pusher;
}


StreamPushServer::StreamPushServer(){
    RegistRPC();
}

StreamPushServer::~StreamPushServer(){

}

void StreamPushServer::RegistRPC(){
    RPCMethodMap method_map;
	method_map.emplace("Start", CRPCFuntion::CreateRpc([this](const Json::Value &request, const BufferMap::Ptr &inMap, Json::Value &response, BufferMap::Ptr &outMap){
		return StartPushStream(request, inMap, response, outMap);
	}));
	
    method_map.emplace("Stop", CRPCFuntion::CreateRpc([this](const Json::Value &request, const BufferMap::Ptr &inMap, Json::Value &response, BufferMap::Ptr &outMap){
		return StopPushStream(request, inMap, response, outMap);
	}));

	IProtocolInterface::GetInstance()->RegistProtocol("PushStream", method_map);
}


bool StreamPushServer::StartPushStream(const Json::Value &request, const Fdt::BufferMap::Ptr &inMap, 
            Json::Value &response, Fdt::BufferMap::Ptr &outBuffer){
    tracef("json------------------------>%s", request.toStyledString().c_str());

    if(!request.isMember("Param") || request["Param"].empty() ){
		return false;
	}
	const Json::Value &param = request["Param"];
	string push_url;
	if(!Json::getJsonString(param, "pushUrl", push_url)){
		tracef("pushUrl error");
		return false;
	}

    string channel;
    if(!Json::getJsonString(param, "channel", channel)){
		tracef("channel error");
		return false;
	}
    
    return IStreamInterface::GetInstance()->StartPushStream(push_url, "live", channel);
}

bool StreamPushServer::StopPushStream(const Json::Value &request, const Fdt::BufferMap::Ptr &inMap, 
        Json::Value &response, Fdt::BufferMap::Ptr &outBuffer){
    tracef("json------------------------>%s", request.toStyledString().c_str());
    string push_url;
    if(request.isMember("Param")){
        const Json::Value &param = request["Param"];
        Json::getJsonString(param, "pushUrl", push_url);
    }

    return IStreamInterface::GetInstance()->StopPushStream(push_url);
}